<template>
  <div class="dev">
    <!-- 搜索框 -->
    <div class="search">
      <el-input
        placeholder="请输入用户名"
        clearable
        prefix-icon="el-icon-search"
        v-model="userName"
      >
      </el-input>
      <el-button type="primary" icon="el-icon-search" @click="search"
        >查找</el-button
      >
      <el-button type="success" icon="el-icon-plus" @click="dialogShow = true"
        >添加</el-button
      >
    </div>
    <!-- 表格数据 -->
    <div class="table">
      <el-table
        :data="tableData"
        ref="isExpand"
        v-loading="loading"
        border
        height="calc(100%-10rem)"
        highlight-current-row
        stripe
        style="width: 100%"
      >
        >
        <template slot="empty">
          <el-empty description="暂无数据"></el-empty>
        </template>
        <el-table-column align="center" prop="userName" label="登录账号">
        </el-table-column>
        <el-table-column align="center" prop="roles" label="角色">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.roles">{{
              scope.row.roles
            }}</el-tag>
            <el-tag v-else>暂无角色</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="phone" label="手机号">
        </el-table-column>
        <el-table-column align="center" prop="createTime" label="创建时间">
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-button type="text" size="small" @click="openCreateFn(scope.row)"
              >设置角色</el-button
            >
            <el-button type="text" size="small" @click="delFn(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        v-show="tableData.length !== 0"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 15, 20, 25, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 添加员工 -->
    <div class="dialog2">
      <el-dialog
        title="添加员工"
        :visible.sync="dialogShow"
        @close="closeOuter(1)"
        width="30%"
      >
        <el-form
          label-position="right"
          :model="addForm"
          :rules="rules"
          ref="addForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model="addForm.userName"
              clearable
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="addForm.password"
              clearable
              show-password
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="surePassword">
            <el-input
              v-model="addForm.surePassword"
              clearable
              show-password
              placeholder="请确认密码"
            ></el-input>
          </el-form-item>

          <el-form-item label="手机号码" prop="phone">
            <el-input
              v-model="addForm.phone"
              clearable
              placeholder="请输入手机号码"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogShow = false">取 消</el-button>
          <el-button type="primary" @click="addFn">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 编辑员工 -->
    <div class="dialog2">
      <el-dialog
        @close="closeOuter(2)"
        title="编辑员工"
        :visible.sync="editDialogShow"
        width="30%"
      >
        <el-form
          label-position="right"
          :model="editForm"
          :rules="rules2"
          ref="editForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="userName">
            <el-input
              disabled
              v-model="editForm.userName"
              clearable
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="editForm.password"
              clearable
              show-password
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="surePassword">
            <el-input
              v-model="editForm.surePassword"
              clearable
              show-password
              placeholder="请确认密码"
            ></el-input>
          </el-form-item>

          <el-form-item label="手机号码" prop="phone">
            <el-input
              v-model="editForm.phone"
              clearable
              placeholder="请输入手机号码"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogShow = false">取 消</el-button>
          <el-button type="primary" @click="editFn">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 给员工设置角色 -->
    <div class="dialog3">
      <el-dialog title="设置角色" :visible.sync="dialogRoles" width="30%">
        <el-form
          label-width="100px"
          :rules="rules"
          ref="role"
          :model="select"
          class="demo-ruleForm"
        >
          <el-form-item prop="selectValue" label="用户角色">
            <el-select
              v-model="select.selectValue"
              filterable
              clearable
              placeholder="请选择角色"
            >
              <el-option
                v-for="item in roleLists"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogRoles = false">取 消</el-button>
          <el-button type="primary" @click="createRoles">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getStaffApi,
  addStaffApi,
  editStaffApi,
  setRolesApi,
  delStaffApi,
  getRolesApi
} from "../../../../api/system/staff";
export default {
  data() {
    var checkpass1 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.addForm.password) {
        callback(new Error("两次输入密码不一致，请重新确认！"));
      } else {
        callback();
      }
    };
    var checkpass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.editForm.password) {
        callback(new Error("两次输入密码不一致，请重新确认！"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: null,
      userName: "",
      dialogShow: false,
      editDialogShow: false,
      dialogRoles: false,
      addForm: {
        password: "",
        phone: "",
        surePassword: "",
        userName: ""
      },
      editForm: {
        password: "",
        phone: "",
        surePassword: ""
      },
      editId: null,
      rules: {
        selectValue: [
          { required: true, message: "请选择角色", trigger: "change" }
        ],
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "请输入3-10位用户名", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "请输入6-15位密码", trigger: "blur" }
        ],
        surePassword: [
          { required: true, message: "请输入确认密码", trigger: "blur" },
          { validator: checkpass1, trigger: "blur" }
        ],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      rules2: {
        userName: [
          { required: false, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "请输入3-10位用户名", trigger: "blur" }
        ],
        password: [
          { required: false, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "请输入6-15位密码", trigger: "blur" }
        ],
        surePassword: [
          { required: false, message: "请输入确认密码", trigger: "blur" },
          { validator: checkpass2, trigger: "blur" }
        ],
        phone: [
          { required: false, message: "请输入手机号码", trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      roles: {
        roleIds: []
      },
      select: {
        selectValue: ""
      },
      roleLists: [],
      userId: null
    };
  },
  created() {
    this.pageSize = Number(sessionStorage.getItem("pageSize")) || 10;
    this.pageNum = Number(sessionStorage.getItem("pageNum")) || 1;
    this.getStaff(this.pageNum, this.pageSize);
  },
  destroyed() {
    sessionStorage.removeItem("pageNum");
    sessionStorage.removeItem("pageSize");
  },
  methods: {
    search() {
      this.pageNum = 1;
      this.getStaff(this.pageNum, this.pageSize, this.userName);
      this.$refs.isExpand.bodyWrapper.scrollTop = 0;
    },
    // 获取员工列表
    getStaff(pageNum, pageSize, userName) {
      this.loading = true;
      getStaffApi(pageNum, pageSize, userName).then(res => {
        this.total = res.data.total;
        if (res.data.rows.length == 0) {
          this.pageNum = this.pageNum - 1;
          if (this.pageNum > 0) {
            this.search();
          } else {
            this.tableData = res.data.rows;
            this.loading = false;
          }
        } else {
          this.loading = false;
          this.tableData = res.data.rows;
        }
      });
    },
    // 分页
    handleSizeChange(val) {
      this.pageNum = 1;
      this.getStaff(this.pageNum, val);
      sessionStorage.setItem("pageSize", val);
      this.pageSize = val;
      this.$refs.isExpand.bodyWrapper.scrollTop = 0;
    },
    handleCurrentChange(val) {
      this.getStaff(val, this.pageSize);
      sessionStorage.setItem("pageNum", val);
      this.pageNum = val;
      this.$refs.isExpand.bodyWrapper.scrollTop = 0;
    },
    // 关闭添加 对话框
    closeOuter(val) {
      if (val == 1) {
        this.addForm = {
          password: "",
          phone: "",
          surePassword: "",
          userName: ""
        };
        // 移除校验结果和数据缓存
        this.$refs.addForm.resetFields();
      } else {
        this.$refs.editForm.resetFields();
      }
    },
    // 添加员工
    addFn() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          addStaffApi(this.addForm)
            .then(res => {
              this.$message.success("添加成功");
              this.dialogShow = false;
              this.search();
            })
            .catch(err => {
              this.$message.error("添加失败");
            });
        } else {
          this.$message.error("填写有误，请重新填写后尝试！");
        }
      });
    },
    // 打开编辑框
    edit(row) {
      // this.editId = e.userId;
      // this.editDialogShow = true;
      // this.editForm = e;
      //   打开弹框传过去的row是Object对象类型，如果直接赋值的话，就变成了浅拷贝，复制的是地址，导致在表单中改变值的时候table中的数据也跟着改变，所以要进行深拷贝。
      this.editDialogShow = true;
      this.editForm = Object.assign(this.editForm, row);
      this.editId = row.userId;
    },
    // 编辑
    editFn() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          let editData = {
            password: this.editForm.password,
            phone: this.editForm.phone,
            surePassword: this.editForm.surePassword
          };
          editStaffApi(this.editId, editData)
            .then(res => {
              this.$message.success("操作成功");
              this.search();
              this.editDialogShow = false;
            })
            .catch(err => {
              this.$message.error("操作失败");
            });
        } else {
          this.$message.error("填写有误，请重新填写后尝试！");
        }
      });
    },
    // 打开设置角色栏,获取角色
    openCreateFn(row) {
      this.userId = row.userId;
      this.dialogRoles = true;
      getRolesApi(row.userId)
        .then(res => {
          this.roleLists = res.data;
          let isOwn = res.data.filter(item => item.isOwn == true);
          if (isOwn.length !== 0) {
            this.select.selectValue = isOwn[0].roleId;
          } else {
            this.select.selectValue = null;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 设置角色
    createRoles() {
      this.roles["roleIds"] = [this.select.selectValue];
      this.$refs.role.validate(valid => {
        if (valid) {
          setRolesApi(this.userId, this.roles)
            .then(res => {
              this.$message.success("设置角色成功");
              this.search();
              this.dialogRoles = false;
            })
            .catch(err => {
              console.log(err);
              this.$message.error("设置角色失败,请选择角色后重新尝试");
            });
        } else {
          this.$message.warning("请先选择角色");
        }
      });
    },
    // 删除
    delFn(e) {
      this.$confirm("确认删除此员工？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          delStaffApi(e.userId)
            .then(res => {
              this.$message.success("删除成功");
              this.search();
            })
            .catch(err => {
              console.log(err);
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message.success("已取消删除");
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.dev {
  padding-top: 15px;
  padding: 0 15px;
  height: calc(100vh - 100px);

  .search {
    margin-bottom: 15px;

    .el-input {
      width: 200px;
    }

    .el-button {
      margin-left: 15px;
    }
  }

  .table {
    height: 100%;

    .el-table {
      height: 70%;
    }

    .el-pagination {
      text-align: center;
      margin-top: 20px;
    }
  }
}
</style>
